let app = getApp();
import { getGoodsInfo, getGoodsParameter, getGoodsSetmeal, checkCollection,grantAuthMobile,
   addCollection, delCollectionByGoodsId, getInsuranceList,getCardList,getGoodsRentSetmeal } from "../../../api";

import { getTelePhone } from "../../../api/shop"
const parse = require("../../../node_modules/mini-html-parser2");
import { disposeData } from "../../../utils/outData";
import { baseImgUrl, programTitle } from "../../../setting";
Page({
  data: {
    goodsId: '',
    goodsInfo: {},
    swiperList: [],
    isShowParameter: false,
    showBottom: false,
    parameterList: [],
    setmealList: [],
    leaseList: [],
    tabs: [
      { id: 0, title: '商品详情' },
      { id: 1, title: '租赁说明' }
    ],
    activeTabId: 0,
    curLease: 0,
    curSetmeal: 0,
    nodes: [],
    labelList: [],
    collectShow: false, //收藏红心状态
    rentNum: 1,
    leaseId: '',   // 租期id
    huabei_stages: '', // 花呗分期数
    setmealId: '', // 套餐id
    huabeiData: {},
    dayRent: '',
    serviceShow: false,
    shop_mobile: '',
    platform_mobile: '',
    selectedPackage: '',
    quantity: '',
    isloading: true,
    is_renewal: '',  //是否续租,
    parent_order_id: '',  //原续租订单号,
    relationId: '',
    order_from: '',
    insuranceList:[],
    unicomList:[],
    insuranceIndex:'',
    unicomIndex:'',
    flag:true,
    flag1:true,
    sale_user_id:'',
    curRent:0,
    buyoutPrice:'0',
    setRentId:1,
    authPhone:'',
  },
  onLoad(option) {                    
    my.removeStorage({ key: 'isAuthShow' });
    const token = my.getStorageSync({ key: 'token' }).data;
    const authPhone = my.getStorageSync({ key: 'authPhone' }).data;

    this.setData({
      goodsId: option.goodsId || disposeData().goodsId,
      order_from: app.globalData.from || 'search',
      // setmealId: option.setmealId || '',
      is_renewal: option.is_renewal || '',
      parent_order_id: option.parent_order_id || '',
      // relationId: disposeData().relationId || '',
      sale_user_id:app.globalData.sale_user_id,
      authPhone
    })
    this.getDetails()
    if(token){
      this.checkIsCollect()
    }
    getInsuranceList().then(res=>{
      this.setData({
        insuranceList:res
      })

      // this.setData({
      //   insuranceIndex:Object.keys(res)[0]
      // })

    })
    getCardList().then(res=>{
      this.setData({
        unicomList:res
      })
    })
    this.getRentSetmeal()
  },
  getDetails() {
    this.setData({ isloading: true })
    getGoodsInfo({
      goods_id: this.data.goodsId,
    }).then(res => {
      if(res.length == 0){
        this.setData({goodsInfo: []})
      } else {
        let imgs = res.carousel_images
        let imgList = []
        if (imgs && imgs.indexOf(",") == -1) {
          imgList.push(imgs)
        } else {
          imgList = imgs ? imgs.split(',') : []
        }
        let contentHtml = res.goods_content.replace(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi, (match, capture) => {
          let newStr = '<img src="' + capture + '" style="width:100%;" alt="" />';
          return newStr;
        });
        parse(contentHtml, (err, nodes) => {
          if (!err) {
            this.setData({
              nodes: nodes,
            })
          }
        })
        let labelArr = res.rent_label ? res.rent_label.replace(/,/g, '，').split('，').filter((p, idx) => p != '' && idx < 2) : [];
        this.setData({
          goodsInfo: res,
          labelList: labelArr,
          swiperList: imgList.map(item => ({ img: item })),
          isloading: false,
        })
      }
    })
  },
  checkIsCollect(){
    checkCollection(this.data.goodsId).then(res =>{
      this.setData({
        collectShow: res.is_collection == 0 ? false : true
      })
    })
  },
  onParBanner(e) {
    const urls = this.data.swiperList.map(item => baseImgUrl + item.img);
    my.previewImage({
      current: e.index,
      urls: urls
    });
  },
  toComplain() {
    my.navigateTo({ url: '../complaints/complaints?goodsTitle=' + this.data.goodsInfo.title});
  },
  toShare() {
    my.showSharePanel();
  },
  checkParameter() {
    getGoodsParameter(this.data.goodsId).then(res => {
      if (res.length > 0) {
        this.setData({
          isShowParameter: !this.data.isShowParameter,
          parameterList: res
        })
      } else {
        my.showToast({
          type: 'none',
          content: '暂无参数',
          duration: 2000
        });
      }
    })
  },
  onPopupClose() {
    this.setData({
      isShowParameter: false,
      showBottom: false,
    })
  },
  // 优惠券
  getCoupon() {},
  jumpStore() {
    const { shopname, member_id } = this.data.goodsInfo
    my.navigateTo({
      url: '../../../pages/storeDetails/storeDetails?shopname=' + shopname + "&member_id=" + member_id
    });
  },
  handleTabClick({ index, tabsName }) {
    this.setData({
      [tabsName]: index,
    });
  },
  toIndex() {
    my.switchTab({ url: '../../../pages/index/index' })
  },
  getAuthorize() {

  },
  closeModal() {
    this.setData({
      serviceShow: false
    })
  },
  goService() {
    getTelePhone(this.data.goodsInfo.member_id).then(res => {
      this.setData({
        serviceShow: true,
        shop_mobile: res.shop_mobile,
        platform_mobile: res.platform_mobile
      })
    })
  },
  callPhone(e) {
    const phone = e.currentTarget.dataset.phone;
    if (phone) {
      my.makePhoneCall({ number: phone })
    }
  },
  goToService() {
    my.switchTab({
      url: '../../../pages/service/service'
    })
  },
  isCollection() {
    const token = my.getStorageSync({ key: 'token' }).data;
    if(token){
      if(!this.data.collectShow){
        addCollection(this.data.goodsId).then(res =>{
          my.showToast({
            type: 'success',
            content: '收藏成功',
            duration: 1000
          });
          this.setData({
            collectShow: true
          })
        })
      } else {
        delCollectionByGoodsId(this.data.goodsId).then(res =>{
          my.showToast({
            type: 'success',
            content: '取消收藏',
            duration: 1000
          });
          this.setData({
            collectShow: false
          })
        })
      }
    } else {
      const that = this
      app.getAuthUser(function (res) {
        if(res){
          that.checkIsCollect()
        }
      })
    }
  },
  collect() {
    this.isCollection()
  },
  getRentSetmeal(){
    getGoodsRentSetmeal(this.data.goodsId).then(res => {
      this.setData({
        rentList: res,
      })
    })
  },
  getSetmeal() {
    getGoodsSetmeal(this.data.goodsId).then(res => {
      let setmealData=res[0];
      const {curLease}=this.data
      if(this.data.curRent=='0'){
        this.setData({
          fixed_first_rent: setmealData.fixed_first_rent,
          fixed_day_price:setmealData.fixed_day_price,
          firstRent: setmealData.fixed_first_rent,
          dayRent:setmealData.fixed_day_price
        })
      }else{
        this.setData({
          fixed_first_rent: setmealData.fixed_first_rent,
          fixed_day_price:setmealData.fixed_day_price,
          firstRent: setmealData.spec ? setmealData.spec[curLease].first_rent : '',
          dayRent:setmealData.spec ? setmealData.spec[curLease].day_price : ''
        })
      }
      this.setData({
        setmealList: res,
        leaseList: res[0].spec,
        huabeiData: res[0].spec[0].huabei_data,
        setmealId: res[0].id,
        leaseId: res[0].spec[0].id,
        totalRent: res[0].spec ? res[0].spec[0].total_amount : '',
        totalValue: res[0].price,
        quantity: res[0].quantity,
        selectedPackage: res[0].title,
        buyoutPrice: res[0].buyout_price,
      })
      // if(this.data.setmealId){
      //   this.setData({
      //     setmealId: this.data.setmealId
      //   })
      // }
    })
  },
  toFreeRent() {
    my.requestSubscribeMessage({
      entityIds: [
        '231599261bf245eba00940aacffa6567',
        '844896d1327d47bda90724942f8ce183',
        'd51c7e6e72e4424cbaf71f59616a208f',
      ],
      success: res => {
        console.log('接口调用成功的回调', res);
      },
      fail: err => {
        console.log('接口调用失败的回调', err);
      }
    });
    this.getSetmeal()
    this.setData({
      showBottom: !this.data.showBottom,
      huabei_stages: '',
      rentNum: 1,
      curSetmeal: 0,
      curLease: 0
    })
  },
  changeRentSetmeal(e) {
    const { curIndex,setRentId } = e.currentTarget.dataset
    const {curLease,leaseList}=this.data

    this.setData({
      curRent: curIndex,
      setRentId: setRentId,
    })
    if(curIndex=='0'){
      this.setData({
        firstRent: this.data.fixed_first_rent,
        dayRent:this.data.fixed_day_price
      })
    }else{
      this.setData({
        firstRent: leaseList ? leaseList[curLease].first_rent : '',
        dayRent:leaseList ? leaseList[curLease].day_price : ''
      })
    }
  },

  changeSetmeal(e) {
    const { curIndex, setmealData } = e.currentTarget.dataset
    const {curLease}=this.data
    console.log(setmealData);
    if(this.data.curRent=='0'){
      this.setData({
        fixed_first_rent: setmealData.fixed_first_rent,
        fixed_day_price:setmealData.fixed_day_price,
        firstRent: setmealData.fixed_first_rent,
        dayRent:setmealData.fixed_day_price
      })
    }else{
      this.setData({
        fixed_first_rent: setmealData.fixed_first_rent,
        fixed_day_price:setmealData.fixed_day_price,
        firstRent: setmealData.spec ? setmealData.spec[curLease].first_rent : '',
        dayRent:setmealData.spec ? setmealData.spec[curLease].day_price : ''
      })
    }

    this.setData({
      rentNum: 1,
      curSetmeal: curIndex,
      huabei_stages: '',
      huabeiData: {},
      setmealId: setmealData.id,
      leaseId: setmealData.spec[curLease].id,
      leaseList: setmealData.spec,
      //curLease: setmealData.spec[curLease].index,
      totalRent: setmealData.spec ? setmealData.spec[curLease].total_amount : '',
      totalValue: setmealData.price,
      buyoutPrice: setmealData.buyout_price,
      quantity: setmealData.quantity,
      selectedPackage: setmealData.title,
    })
    if(setmealData.spec.length >0 && setmealData.spec[0].huabei_data){
      this.setData({
        huabeiData: setmealData.spec[0].huabei_data
      })
    }
  },
  changeLease(e) {
    const { leaseIndex, huabeiObj, leaseTime, leaseId } = e.currentTarget.dataset
    if(huabeiObj && huabeiObj.length){
      huabeiObj.forEach(item =>{
        if(leaseTime == item.lease_term){
          item.three_select = false
          item.six_select = false
          item.twelve_select = false
          this.setData({
            huabeiData: item
          })
        }
      })
    }
    this.data.leaseList.forEach(item =>{
      if(leaseId == item.id){
        this.setData({
          dayRent: item.day_price,
          firstRent: item.first_rent,
          totalRent: item.total_amount
        })
      }
    })
    this.setData({
      curLease: leaseIndex,
      leaseId: leaseId
    })
  },
  changeInsurance(e) {
    const { leaseIndex, huabeiObj, leaseTime, leaseId, insuranceIndex} = e.currentTarget.dataset
    if(this.data.insuranceIndex==insuranceIndex){
      this.setData({
        insuranceIndex:''
      })
    }else{
      this.setData({
        insuranceIndex:insuranceIndex
      })
    }
  },
  changeunicom(e) {
    const { leaseIndex, huabeiObj, leaseTime, leaseId, unicomIndex} = e.currentTarget.dataset
    if(this.data.unicomIndex==unicomIndex){
      this.setData({
        unicomIndex:''
      })
    }else{
      this.setData({
        unicomIndex:unicomIndex
      })
    }
  },
  changeHuabei(e){
    let huabei = e.currentTarget.dataset.huabei
    let obj = {...this.data.huabeiData}
    if(huabei == 3){
      obj.three_select = !obj.three_select
      obj.six_select = false
      obj.twelve_select = false
    } else if (huabei == 6){
      obj.three_select = false
      obj.six_select = !obj.six_select
      obj.twelve_select = false
    } else if (huabei == 12){
      obj.three_select = false
      obj.six_select = false
      obj.twelve_select = !obj.twelve_select
    }
    this.setData({
      huabeiData: obj
    })
    if(!obj.three_select && !obj.six_select && !obj.twelve_select ){
      this.setData({
        huabei_stages: ''
      })
    } else {
      this.setData({
        huabei_stages: huabei
      })
    }
  },
  getAuthPhone() {
    const token = my.getStorageSync({ key: 'token' }).data;
    if (!token) {
      app.getAuthUser(function (res) {
        if (res) {
          this.getPhone()
        }
      })
    } else {
      this.getPhone()
    }
  },
  getPhone() {
    const that = this
    my.getPhoneNumber({
      success: (res) => {
        let encryptedData = JSON.parse(res.response).response;
        grantAuthMobile(encryptedData).then(res => {
          if (res) {
            my.setStorage({ key: 'authPhone', data: res.mobile })
            that.setData({ authPhone: res.mobile })
            my.showToast({
              type: 'success',
              content: '获取手机号成功',
            })
            // this.submitOrder()
          } else {
            my.showToast({
              type: 'fail',
              content: '获取手机号失败,请稍后重试',
              duration: 1500,
            })
          }
        })
      },
    });
  },
  changeNumber(value) {
    this.setData({
      rentNum: value,
    });
  },
  goBuy() {
    const that = this
    const token = my.getStorageSync({ key: 'token' }).data;
    const { goodsInfo, goodsId, setmealId, leaseId, rentNum, huabei_stages, quantity, is_renewal, relationId, parent_order_id, order_from,sale_user_id ,insuranceIndex,setRentId} = that.data;
    if(quantity < 1){
      my.showToast({
        type: 'none',
        content: '库存不足',
        duration: 1500,
      });
      return
    }
    if(token){
      my.navigateTo({
        url: '../makeOrder/makeOrder?goodsId=' +goodsId+ "&setmealId=" +setmealId+ "&leaseId=" +leaseId+ '&parent_order_id=' +parent_order_id+
          "&num=" +rentNum+ "&isShow=" +goodsInfo.is_show+ "&huabei_stages=" +huabei_stages+ "&isRenewal=" +is_renewal+ '&relationId=' +relationId+ '&from=' +order_from+'&insurance='+this.data.insuranceIndex
          +'&sale_user_id='+app.globalData.sale_user_id+'&unicom='+this.data.unicomIndex+'&pact_type='+this.data.setRentId
      });
      this.setData({ showBottom: false })
    } else {
      app.getAuthUser(function (res) {
        if(res){
          that.setData({ showBottom: false })
          my.navigateTo({
              url: '/pagesA/pages/makeOrder/makeOrder?goodsId=' +goodsId+ "&setmealId=" +setmealId+ "&leaseId=" +leaseId+ '&parent_order_id=' +parent_order_id+
              "&num=" +rentNum+ "&isShow=" +goodsInfo.is_show+ "&huabei_stages=" +huabei_stages+ "&isRenewal=" +is_renewal+ '&relationId=' +relationId+ '&from=' +order_from+'&insurance='+insuranceIndex
              +'&sale_user_id='+app.globalData.sale_user_id+'&pact_type='+setRentId
            });
        }
      })
    }
  },
  onShareAppMessage() {
    // 返回自定义分享信息
    return {
      title: this.data.goodsInfo.title,
      desc: this.data.goodsInfo.spread_title,
      searchTip: programTitle,
      content: '选择'+programTitle+'，生活没烦恼',
      path: 'pagesA/pages/productDetails/productDetails?from=qrcode&goodsId='+this.data.goodsId,
    };
  }
});
